package v2;

import lombok.Data;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.wltea.analyzer.lucene.IKAnalyzer;

import java.util.UUID;


/**
 * Search Object
 */
@Data
public class ObjectSO {

    private final static IKAnalyzer analyzer = new IKAnalyzer();
    private String title;
    private String content;

    public static ObjectSO of(String title, String content) {
        ObjectSO objectSO = new ObjectSO();
        objectSO.setTitle(title);
        objectSO.setContent(content);
        return objectSO;
    }

    public Document toDoc() {
        Document doc = new Document();
        doc.add(new TextField("title", title, Field.Store.YES));
        doc.add(new TextField("content", content, Field.Store.YES));
        doc.add(new StringField("uuid", UUID.randomUUID().toString(), Field.Store.YES));
        return doc;
    }

    public ObjectSO fromDoc(Document doc) {
        title = doc.get("title");
        content = doc.get("content");
        return this;
    }

//    public static void main(String[] args) throws IOException, ParseException {
//
//        //index
//        File indexPath = new File("/home/tom/.index_obj/");
//        FSDirectory dir = FSDirectory.open(indexPath);
//        dir.setReadChunkSize(2 << 20);//100兆
//        IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_40, analyzer);
//        config.setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND);
//        IndexWriter writer = new IndexWriter(dir, config);
//        try {
//            writer.addDocument(of("你好", "你不好").toDoc());
//            writer.addDocument(of("你好2 " + System.currentTimeMillis(), "你不好2").toDoc());
//            writer.forceMerge(100);
//            writer.commit();
//        } finally {
//            close(writer);
//            close(dir);
//        }
//        System.out.println("add document os");
//
//
//        IndexReader indexReader = DirectoryReader.open(FSDirectory.open(indexPath));
//        IndexSearcher searcher = new IndexSearcher(indexReader);
//
//
//        QueryParser parser2 = new QueryParser(Version.LUCENE_40, "content", analyzer);
//        Query query = parser2.parse("646d0a4c-3200-4efa-8318-056eca37ff42");
//
////        TermQuery query = new TermQuery(new Term("content", "你好"));
//        query.setBoost(1.0f);
//        TopDocs topDocs = searcher.search(query, 100);
//        ScoreDoc[] scoreDocs = topDocs.scoreDocs;
//        for (ScoreDoc scoreDoc : scoreDocs) {
//            Document doc = searcher.doc(scoreDoc.doc);
//            System.out.println("doc:" + doc);
//        }
//
//        indexReader.close();
//
//    }
}
